package jf.jextn.util;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import jf.jextn.JExtn;

public class DateUtil {
    public static final Calendar FIRST_JAN_1970;

    static {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, 1970);
        cal.set(Calendar.MONTH, Calendar.JANUARY);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        FIRST_JAN_1970 = cal;
    }

    public static final Pattern TIME_HH24MM = Pattern.compile("^([0-1][0-9]|[2][0-3]):([0-5][0-9])$");

    public static long difference(Date date1, Date date2, TimeUnit unit) {
        long ms1 = date1.getTime();
        long ms2 = date2.getTime();

        long diff = Math.abs(ms1 - ms2);

        return unit.convert(diff, TimeUnit.MILLISECONDS);
    }

    public static void clearTime(Calendar calendar) {
        if (calendar != null) {
            calendar.clear(Calendar.HOUR_OF_DAY);
            calendar.clear(Calendar.MINUTE);
            calendar.clear(Calendar.SECOND);
            calendar.clear(Calendar.MILLISECOND);
        }
    }

    /**
     * Parse the passed time and return the pair of hours and minutes.
     *
     * @param hhmm
     *            time in HH:MM format
     * @return pair of having integer values for hour and minutes
     * @throws IllegalArgumentException
     *             if illegal argument is passed.
     */
    public static Pair<Integer, Integer> parseTimeHHMM(String hhmm) {
        if (JExtn.isNullOrBlank(hhmm) || !TIME_HH24MM.matcher(hhmm).matches()) {
            throw new IllegalArgumentException("Time should be in HH24:MM format. e.g. 02:04 | 16:56 | 23:59");
        }

        String[] split = hhmm.split(":");

        return JExtn.newPair(Integer.valueOf(split[0]), Integer.valueOf(split[1]));
    }

}
